package ssm.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ssm.mapper.CartMapper;
import ssm.mapper.UserMapper;
import ssm.pojo.Cart;
import ssm.pojo.CartItem;
import ssm.pojo.User;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Service
public class CartService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private UserSerivce userSerivce;

    public User addCart(Integer bookId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Cart cart = user.getCart();
        Map<Integer, CartItem> cartItemMap = cart.getCartItemMap();
        CartItem cartItem = cartItemMap.get(bookId);
        if (cartItem==null){
            cartMapper.addCartItem(bookId,user.getUid());
        }else {
            cartMapper.updateCartItem(bookId,cartItem.getBuyCount()+1,user.getUid());
        }
        user = userSerivce.getUser(user.getUname(), user.getPwd());
        return user;
    }

    public User updateCartAdd(Integer bookId,HttpSession session){
        User user = (User) session.getAttribute("user");
        Cart cart = user.getCart();
        Map<Integer, CartItem> cartItemMap = cart.getCartItemMap();
        CartItem cartItem = cartItemMap.get(bookId);
        cartMapper.updateCartItem(bookId,cartItem.getBuyCount()+1,user.getUid());
        user = userSerivce.getUser(user.getUname(), user.getPwd());
        return user;
    }
    public User updateCartMove(Integer bookId,HttpSession session){
        User user = (User) session.getAttribute("user");
        Cart cart = user.getCart();
        Map<Integer, CartItem> cartItemMap = cart.getCartItemMap();
        CartItem cartItem = cartItemMap.get(bookId);
        cartMapper.updateCartItem(bookId,cartItem.getBuyCount()-1,user.getUid());
        user = userSerivce.getUser(user.getUname(), user.getPwd());
        return user;
    }

    public User deleteCartItem(Integer bookId,HttpSession session){
        User user = (User) session.getAttribute("user");
        cartMapper.deleteCartItem(bookId,user.getUid());
        user = userSerivce.getUser(user.getUname(), user.getPwd());
        return user;
    }

    public User clearCartItem(HttpSession session){
        User user = (User) session.getAttribute("user");
        cartMapper.clearCartItem(user.getUid());
        user = userSerivce.getUser(user.getUname(), user.getPwd());
        return user;
    }

}
